<template>
  <div class="search-container">
      <!-- 在 van-search 外层增加 form 标签，且 action 不为空，即可在 iOS 输入法中显示搜索按钮。 -->
    <form action="/">
      <van-search
        v-model="searchText"
        placeholder="请输入搜索关键词"
        show-action
        @search="onSearch(searchText)"
        @cancel="$router.back()"
        @focus="isResultShow=false"
      />
    </form>
    <search-result v-if="isResultShow" :search-text="searchText" />
    <search-suggestion v-else-if="searchText" :search-text="searchText" @search="onSearch" />
    <search-history v-else :searchHistories="searchHistories" @search="onSearch" @update-histories="searchHistories=$event" />
  </div>
</template>
<script>
import SearchSuggestion from './components/search-suggestion.vue'
import SearchHistory from './components/search-history.vue'
import SearchResult from './components/search-result.vue'
import {getItem,setItem} from '@/utils/storage'
// import {getSearchHistories} from '@/api/search'
import {mapState} from 'vuex'
export default {
  name: "SearchIndex",
  components:{
      SearchSuggestion,
      SearchHistory,
      SearchResult
  },
  created(){
    this.loadSearchHistories()
  },
  watch:{
    // 监视搜索历史记录的变化，存储到本地存储
    searchHistories(){
      setItem('search-histories',this.searchHistories)
    }
  },
  computed:{
    ...mapState(['user'])
  },
  data() {
    return {
      searchText:'',
      isResultShow:false,
      searchHistories:getItem('search-histories')||[]
    };
  },
  methods: {
    onSearch(searchText) {
      // 把输入框设置为要搜索的内容
      this.searchText=searchText
      // 记录搜索历史记录
      const index=this.searchHistories.indexOf(searchText)
      if(index!==-1){
        // 把重复项删除
        this.searchHistories.splice(index,1)
      }
      // 把最新的搜索记录放在顶部
      this.searchHistories.unshift(searchText)
      setItem('search-histories',this.searchHistories)
      this.isResultShow=true
    },
    //   onCancel(){

    //   }
    async loadSearchHistories(){
     const searchHistories=getItem('search-histories')||[]
      // if(this.user){
      //   const {data}=await getSearchHistories()
      //  searchHistories=[...new Set([
      //    ...searchHistories,
      //    ...data.data.keywords
      //  ])]
      // }
     this.searchHistories=searchHistories
    }
  },
};
</script>
<style scoped lang="less">
</style>